<template>
  <BasicTable @register="registerTable" :rowSelection="rowSelection">
    <template #tableTitle>
      <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleCreate"> 新增菜单</a-button>
      <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleOpenScene"> 场景管理</a-button>
      <a-button type="primary" preIcon="ic:round-expand" @click="expandAll">展开全部</a-button>
      <a-button type="primary" preIcon="ic:round-compress" @click="collapseAll">折叠全部</a-button>

      <a-dropdown v-if="checkedKeys.length > 0">
        <template #overlay>
          <a-menu>
            <a-menu-item key="1" @click="batchHandleDelete">
              <Icon icon="ant-design:delete-outlined" />
              删除
            </a-menu-item>
          </a-menu>
        </template>
        <a-button>批量操作
          <Icon icon="ant-design:down-outlined" />
        </a-button>
      </a-dropdown>
    </template>
    <template #action="{ record }">
      <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
    </template>
  </BasicTable>
  <MenuDrawer @register="registerDrawer" @success="handleSuccess" :showFooter="showFooter" />
  <DataRuleList @register="registerDrawer1" />
  <CopyMenu @register="registerCopyMenu" @success="reload"/>
  <SceneListDrawer @register="registerSceneListDrawer"/>
</template>
<script lang="ts" name="system-menu" setup>
import { nextTick, ref, onMounted } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { useListPage } from '/@/hooks/system/useListPage'
import { useDrawer } from '/@/components/Drawer';
import MenuDrawer from './MenuDrawer.vue';
import SceneListDrawer from '/@/views/system/scene/SceneListDrawer.vue';
import CopyMenu from './CopyMenu.vue';
import DataRuleList from './DataRuleList.vue';
import { columns, searchFormSchema } from './menu.data';
import { list, deleteMenu, batchDeleteMenu } from './menu.api';
import { useRouter } from "vue-router"
import { useMessage } from '/@/hooks/web/useMessage';
import { listScene } from "/@/api/sys/scene";
import { Icon } from '/@/components/Icon';
import { useUserStore } from '/@/store/modules/user';
import { useModal } from '/@/components/Modal';

const userStore = useUserStore()
const selectTenant = userStore.getSelectTenant
const { createMessage } = useMessage();
const router = useRouter()
let appId = router.currentRoute.value.query?.appId

const checkedKeys = ref<Array<string | number>>([]);
const showFooter = ref(true);
const [registerDrawer, { openDrawer }] = useDrawer();
const [registerDrawer1, { openDrawer: openDataRule }] = useDrawer();
const [registerSceneListDrawer, { openDrawer: openSceneListDrawer }] = useDrawer();

const [registerCopyMenu, { openModal: openCopenMenu }] = useModal();

const { prefixCls, tableContext } = useListPage({
  tableProps: {
    title: '菜单列表',
    api: list,
    immediate: false,
    beforeFetch: (params) => {
      params.appId = appId
    },
    formConfig: {
      labelWidth: 90,
      schemas: searchFormSchema,
    },
    columns: columns,
    size: 'small',
    pagination: false,
    isTreeTable: true,
    striped: true,
    useSearchForm: true,
    showTableSetting: true,
    bordered: false,
    showIndexColumn: false,
    tableSetting: { fullScreen: true },
    actionColumn: {
      width: 150,
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      slots: { customRender: 'action' },
    },
  }
})

const [registerTable, { reload, getForm, expandAll, collapseAll }] = tableContext

/**
 * 选择列配置
 */
const rowSelection = {
  type: 'checkbox',
  columnWidth: 30,
  selectedRowKeys: checkedKeys,
  onChange: onSelectChange,
};

onMounted(() => {
  const { updateSchema, setFieldsValue } = getForm()

  if (selectTenant?.isMgtSceneTenant && !userStore.getIsSysAdminTenant) {
    setFieldsValue({ sceneId: selectTenant.sceneId })
    reload()
  } else {
    updateSchema([
      {
        field: 'sceneId',
        componentProps:  ({ formModel, formActionType }) =>{
          const {setFieldsValue} = formActionType
          return {
            optionFilterProp: "label",
            showSearch: true,
            api: listScene,
            onOptionsChange: (options) => {
              if (options && options.length > 0) {
                setFieldsValue({ sceneId: options[0].value })
                reload()
              }
            },
            onSelect: (value: any, option: any) => {
              console.log("option", option);
              setFieldsValue({sceneId: option.value})
              reload()
            },
          }
        },
        colProps: { span: 8 },
      },
    ])
  }
  
})

const handleOpenScene = () => {
  openSceneListDrawer(true, {
    isUpdate: true
  });
}
/**
 * 选择事件
 */
function onSelectChange(selectedRowKeys: (string | number)[]) {
  checkedKeys.value = selectedRowKeys;
}

/**
 * 新增
 */
function handleCreate() {
  console.time('menu-drawer')
  showFooter.value = true;
  const sceneId = getSceneId()
  if (!sceneId) {
    console.log('sceneId: ', sceneId)
    return
  }
  openDrawer(true, {
    isUpdate: false, appId, sceneId,
  });
}

const getSceneId = () => {
  const { getFieldsValue } = getForm();
  const sceneId = getFieldsValue().sceneId;
  if (!sceneId) {
    createMessage.warning('请选择场景')
    return
  }
  return sceneId
}

/**
 * 编辑
 */
function handleEdit(record) {
  console.time('menu-drawer')
  showFooter.value = true;
  const sceneId = getSceneId()
  if (!sceneId) {
    return
  }

  openDrawer(true, {
    record,
    appId,
    sceneId,
    isUpdate: true,
  });
}
/**
 * 详情
 */
function handleDetail(record) {
  showFooter.value = false;
  openDrawer(true, {
    record,
    isUpdate: true
  });
}
/**
 * 添加下级
 */
function handleAddSub(record) {
  const sceneId = getSceneId()
  if (!sceneId) {
    return
  }
  openDrawer(true, {
    record: { 'parentId': record.id, 'menuType': "1" },
    appId, sceneId,
    isUpdate: false,
  });
}
/**
 * 数据权限弹窗
 */
function handleDataRule(record) {
  openDataRule(true, { id: record.id })
}

/**
 * 删除
 */
async function handleDelete(record) {
  await deleteMenu({ id: record.id }, reload);
}

async function handleCopyMenu(record) {
  openCopenMenu(true, {record})
}

/**
 * 批量删除事件
 */
async function batchHandleDelete() {
  await batchDeleteMenu({ ids: checkedKeys.value }, reload);
}
/**
 * 成功回调
 */
function handleSuccess() {
  reload();
}

function onFetchSuccess() {
  // 演示默认展开所有表项
  nextTick(expandAll);
}



/**
 * 操作栏
 */
function getTableAction(record) {
  return [
    {
      label: '编辑',
      onClick: handleEdit.bind(null, record),
    },
    {
      label: '删除',
      color: 'error',
      popConfirm: {
        title: `是否确认删除 ${record.name}`,
        confirm: handleDelete.bind(null, record),
      },
    },
  ];
}

/**
 * 下拉操作栏
 */
function getDropDownAction(record) {
  return [
    {
      label: '详情',
      onClick: handleDetail.bind(null, record),
    },
    {
      label: '复制',
      onClick: handleCopyMenu.bind(null, record),
    },
    {
      label: '添加下级',
      onClick: handleAddSub.bind(null, record),
    },
    {
      label: '数据规则',
      onClick: handleDataRule.bind(null, record),
    },
    
  ];
}
</script>
